/*
 * Created on 2008-06-04
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package elka.isi.operator;

import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import elka.isi.individual.AnimalIndividual;
import elka.isi.individual.HerbivoreAnimalIndivdual;
import elka.isi.individual.RabbitIndividual;
import elka.isi.util.RWUtils;
import org.evolvica.core.IIndividual;
import org.evolvica.core.IIndividualSet;
import org.evolvica.core.IndividualList;
import org.evolvica.core.population.SortedPopulation;
import org.evolvica.util.RandomUtils;

import elka.isi.individual.HerbivoreAnimalIndivdual;
import elka.isi.individual.WolfIndividual;
import elka.isi.util.RWUtils;

/**
 * @author Zibi
 * 
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public class HuntingEcosystem extends SortedEcosystem {

	/*
	 * (non-Javadoc)
	 * 
	 * @see elka.isi.SortedEcosystem#insert(org.evolvica.core.IIndividualSet)
	 */

	public IIndividualSet insert(IIndividualSet iset) {
		// RWUtils.getActualStats(iset);

		List huntingWolves =
			Arrays.asList(RWUtils.getWolves(iset).toArray());
		Collections.sort(huntingWolves, comparator);

		IIndividual[] rabbits = RWUtils.getRabbits(iset).toArray();
		IIndividual[] roes = RWUtils.getRoes(iset).toArray();
		IIndividualSet herbivoesToKill = new IndividualList();
		for (Iterator iterator = huntingWolves.iterator();
			iterator.hasNext();
			) 
		{
			AnimalIndividual individualWolf =
				(AnimalIndividual) iterator.next();
			//IIndividual[] wolves = RWUtils.getWolves(iset).toArray();

			IIndividualSet weakerHerbivoes =
				RWUtils.getWeaker(rabbits, individualWolf, comparator);
			weakerHerbivoes.add(
				RWUtils.getWeaker(roes, individualWolf, comparator).toArray());

			//todo: prosba o komentarz jaka byla idea / Jacek
			//na razie uzywam jednego catchRatio dla krolikow i saren
			IIndividual individual;
			IIndividualSet toRetrieveIndividual;
			int unitOfFoodEaten = 0;
			int unitOfFoodOfOne = 0;
			while (unitOfFoodEaten < wolfApetite) {

				toRetrieveIndividual =
					RWUtils.getRandomIndividuals(weakerHerbivoes, 1);
				//if(RandomUtils.randomInt(2) == 0) continue;
				if (toRetrieveIndividual.size() != 0) {
					individual = (toRetrieveIndividual.toArray())[0];
					unitOfFoodOfOne = 1 + (int) ((((HerbivoreAnimalIndivdual) individual).getNutritionalScore())) / 10;
					unitOfFoodEaten += unitOfFoodOfOne;
					weakerHerbivoes.remove(individual);
					iset.remove(individual);
				} else
					break;
			}
			if (unitOfFoodEaten < wolfApetite) {
				iset.remove(individualWolf);
			}
		}
		++generation; // increment generation counter
		RWUtils.getActualStats(iset);
		return iset;
	}

}
